package com.nwpu.bigdata.util.impl;
/**
 *@version:2018年4月23日下午9:08:22
*/
/**
 * @author Administrator
 *
 */

import org.influxdb.InfluxDB;


import org.influxdb.dto.Point;
import org.influxdb.dto.Query;
import org.influxdb.dto.QueryResult;

import java.util.Map;
public class InfluxdbService {

    private String database;
    private String policyName;
    private InfluxDB influxDB;

    public InfluxdbService(String database, String policyName, InfluxDB influxDB) {
        this.database = database;
        this.policyName = policyName;
        this.influxDB = influxDB;
    }

    public void createDatabase(){
        influxDB.createDatabase(database);//创建数据库
    }

    /**
     *  建保存策略
     * @param duration 存放时间
     * @param replicationNum　备份数量
     */
    public void createRetentionPolicy(String duration, Integer replicationNum){
        String cmd = String.format("CREATE RETENTION POLICY %s ON %s DURATION %s REPLICATION %s DEFAULT",policyName,database,duration,replicationNum);
        //数据保留策略
        influxDB.query(new Query(cmd,database));
    }


    public QueryResult query(String cmd){
        return influxDB.query(new Query(cmd,database));
    }

    /**
     * 插入数据
     * @param measurement　表名
     * @param tags
     * @param fields
     */
    public void insert(String measurement,Map<String,String> tags,Map<String,Object> fields){
        Point.Builder builder = Point.measurement(measurement).tag(tags);
        if(fields != null && !fields.isEmpty()){
            builder.fields(fields);
        }
        influxDB.write(database,policyName,builder.build());
    }

    public String getDatabase() {
        return database;
    }

    public String getPolicyName() {
        return policyName;
    }

    public InfluxDB getInfluxDB() {
        return influxDB;
    }
}